<template>
  <div>
    <div>
      <el-input size="small" placeholder="请输入标签" v-model="labelType" clearable style="width: 50%"></el-input>
      <el-button type="primary" size="small" style="margin-left: 10px;" @click="addTag">添加</el-button>
    </div>
    <div>
      <el-tag v-for="tag in tagList" :key="tag.name" closable @close="deleteTag(tag)" style="margin-right: 5px;">
        {{tag}}
      </el-tag>
    </div>
  </div>
</template>

<script>

export default {
  name: 'index',
  props: {
    value: {
      type: [String, Array],
      default: ''
    }
  },
  data() {
    return {
      labelType: '',
      tagList: []
    }
  },
  watch: {
    value: {
      handler: async function(val) {
        if (val) {
          if (Array.isArray(val)) {
            this.tagList = val
          } else {
            this.tagList = val.split(',');
          }
        } else {
          this.tagList = []
          return []
        }
      },
      deep: true,
      immediate: true
    }
  },
  created() {
  },
  methods: {
    /** 动态添加标签 */
    addTag() {
      if (this.labelType) {
        if (this.tagList.indexOf(this.labelType) > -1) {
          this.$message({
            type: 'warning',
            message: '不能添加重复的类型标签'
          });
        } else {
          this.tagList.push(this.labelType);
          this.$emit("input", this.listToString(this.tagList));
          this.labelType = '';
        }
      }
    },
    /** 动态删除标签 */
    deleteTag(tag) {
      this.tagList.splice(this.tagList.indexOf(tag), 1);
      this.$emit("input", this.listToString(this.tagList));
    },
    /** 对象转成指定字符串分隔 */
    listToString(list, separator) {
      let strs = "";
      separator = separator || ",";
      for (let i in list) {
        if (list[i]) {
          strs += list[i] + separator;
        }
      }
      return strs != "" ? strs.substr(0, strs.length - 1) : "";
    }
  }
}
</script>

<style scoped>

</style>
